<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * 用户账单
 * Class UserBill
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $uid 用户编号
 * @property integer $start_time 开始时间
 * @property integer $end_time 结束时间
 * @property float $money 金额
 * @property integer $is_check 是否结算
 * @property integer $create_time 创建时间
 * @property integer $check_time 结算时间
 */
class UserBill extends ActiveRecord
{
    /**
     * 生成用户上个月的账单
     * 每月1号执行一次
     */
    public static function taskGenerateNewBill()
    {
        $monthStartTime = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
        $monthEndTime = strtotime(strtotime(date('Y-m-01 00:00:00')) - 1);
        /** @var User $user */
        foreach (User::find()
            ->andWhere(['status' => User::STATUS_OK])
            ->each() as $user) {
            $money = 0;
            /** @var Card $card */
            foreach (Card::find()
                ->andWhere(['uid' => $user->id])
                ->each() as $card) {
                $cardBasic = CardBasic::findOne(['card_id' => $card->id]);
                if (empty($cardBasic)) {
                    continue;
                }
                if ($cardBasic->status != 'ACTIVATED_NAME') {
                    continue;
                }
                // TODO：更新上个月的卡账单，考虑使用FTP报表功能
                /** @var CardBill $cardBill */
                $cardBill = CardBill::find()
                    ->andWhere(['card_id' => $card->id])
                    ->andWhere(['start_time' => $monthStartTime])
                    ->one();
                if (empty($cardBill)) {
                    Yii::error('生成账单时没有找到卡账单【' . $card->iccid . '】。');
                    continue;
                }
                $money += $cardBill->money;
            }
            $userBill = new UserBill();
            $userBill->uid = $user->id;
            $userBill->start_time = $monthStartTime;
            $userBill->money = $money;
            $userBill->is_check = $monthEndTime;
            $userBill->create_time = time();
            $userBill->save();
        }
    }
}
